import React, { useRef, useState } from "react";
import add from "../../assets/images/add1.webp";
import "./style.css";
import { message } from "antd";
const Index = () => {
  const input = useRef<HTMLInputElement | null>(null);
  
  const [url, setUrl] = useState("");
  const onClick = () => {
    if (input.current) input.current.click();
  };

  const onChange = () => {
    if (input.current) {
      // 获取上传的文件列表
      const files = input.current.files;
      if (files) {
        // 获取上传的文件
        const file = files[0];
        // 创建文件读取容器
        const fileReader = new FileReader();
        // 读取文件  base64 读取
        fileReader.readAsDataURL(file);
        // 读取完毕事件
        fileReader.addEventListener("load", () => {
          if (fileReader.result) setUrl(fileReader.result as string);
        });
      } else {
        message.error("上传的文件不存在");
      }
    }
  };

  return (
    <div>
      <div className="upload" onClick={() => onClick()}>
        <img src={url || add} alt="" className="upload-avator" />
        <input
          ref={input}
          type="file"
          style={{ display: "none" }}
          onChange={() => onChange()}
        />
      </div>
    </div>
  );
};

export default Index;
